"""
@Author：十
@Time：2024/8/5 11:24
@FileName：export.py
@Description： 报告导出实现
"""
import os
import shutil
import sys

from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QApplication, QFileDialog, QMessageBox
from docx import Document
from pyqt5_plugins.examplebutton import QtWidgets
from UI.export import Ui_Form


class ExportWindow(QtWidgets.QWidget, Ui_Form):
    # 到处报道时将数据传递到窗口
    Signal_Position_Data = pyqtSignal(object, object)

    def __init__(self, parent=None):
        super(ExportWindow, self).__init__()

        self.parent = parent

        self.setupUi(self)

        self.pushButton.clicked.connect(self.GetPath)

        self.Signal_Position_Data.connect(self.GetTestData)

        self.pushButton_Config.clicked.connect(self.GetData)

        self.pushButton_Config.setEnabled(False)

        # 保存表格数据
        self.all_data = []
        # 设备名
        self.instrument = ''

    def GetPath(self):
        try:
            file = QFileDialog.getExistingDirectory(None, "选取文件夹", "C:/")
            self.lineEdit_FilePath.setText(file)
            if file:
                self.pushButton_Config.setEnabled(True)
        except Exception as e:
            print('Open File Error', e)

    # 获取主界面表格数据
    def GetTestData(self, all_data, instrument):
        self.all_data = all_data
        self.instrument = instrument

    def GetData(self):
        file_name = 'report.docx'
        headers = []
        table_length = len(self.all_data)
        try:
            location = self.lineEdit_Loaction.text()
            type_ = self.lineEdit_Type.text()
            voltage = self.lineEdit_Voltage.text()
            factory = self.lineEdit_Factory.text()
            number = self.lineEdit_Number.text()
            file = self.lineEdit_FilePath.text()
            if file is None:
                QMessageBox.warning(self, '标题', '请选择报告保存路径', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
            print(location, type_, voltage, factory, number, file)
            if self.instrument == '直流电阻测试仪':
                file_name = "直流电阻测试仪报告" + '.docx'

            template_path = os.path.join(os.getcwd(), 'report', 'ListReport.docx')
            target_path = os.path.join(file, file_name)

            if not os.path.exists(template_path):
                print(f"Template file not found: {template_path}")
                return

            counter = 1
            while os.path.exists(target_path):
                target_path = os.path.join(file, f'直流电阻测试仪报告_{counter}.docx')
                counter += 1

            try:
                shutil.copy(template_path, target_path)

                doc = Document(target_path)

                paragraphs = doc.paragraphs
                for i in range(len(paragraphs)):
                    if '装设位置：' in paragraphs[i].text and '设备型号：' in paragraphs[i].text:
                        paragraphs[i].text = f'装设位置：{location}  设备型号：{type_}  额定电压：{voltage}'
                    elif '生产厂家：' in paragraphs[i].text and '编号：' in paragraphs[i].text:
                        paragraphs[i].text = f'生产厂家：{factory}  编号：{number}'
                        break

                for paragraph in doc.paragraphs:
                    if '2、试验数据记录' in paragraph.text and table_length > 0:
                        table = doc.add_table(rows=table_length + 1, cols=len(self.all_data[0]))
                        hdr_cells = table.rows[0].cells
                        if self.instrument == '直流电阻测试仪':
                            headers = ["测试时间", "测试模式", "测试电流", "电阻A", "电阻B", "电阻C", "最大不平衡率"]
                        for i, header in enumerate(headers):
                            hdr_cells[i].text = header

                        for row_index, row_data in enumerate(self.all_data):
                            row_cells = table.rows[row_index + 1].cells
                            for col_index, cell_data in enumerate(row_data):
                                row_cells[col_index].text = cell_data

                        paragraph._element.addnext(table._element)
                        break

                doc.save(target_path)
                # print(f"Report saved to: {target_path}")
                QMessageBox.about(self, '成功', f'数据已保存到\n{target_path}')
                self.close()

            except Exception as e:
                print(f"An error occurred while saving the report: {e}")

        except Exception as e:
            print('生成报告错误：', e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = ExportWindow()
    mainWindow.show()
    sys.exit(app.exec_())
